package cn.shadow.module.snake;

import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;

public class Bullet extends Actor {
    private TextureRegion bullet;
    private Snake snake;
    private float x;
    private float y;
    private int speed;
   private SnakeNode.Direction direction;
    private float limitX;
    private float limitY;

    public Bullet(float x, float y, TextureRegion bullet, SnakeNode.Direction direction, float limitX, float limitY, int speed) {
        this.bullet = bullet;
        this.x = x;
        this.y = y;
        this.speed = speed;
        this.direction = direction;
        this.limitX = limitX;
        this.limitY = limitY;
        setSize(this.bullet.getRegionWidth(), this.bullet.getRegionHeight());
        setPosition(x,y);
    }

    public TextureRegion getBullet() {
        return bullet;
    }

    public void setBullet(TextureRegion bullet) {
        this.bullet = bullet;
    }

    public Snake getSnake() {
        return snake;
    }

    public void setSnake(Snake snake) {
        this.snake = snake;
    }

    public int getSpeed() {
        return speed;
    }

    public void setSpeed(int speed) {
        this.speed = speed;
    }

    /**
     * 从目标处发出去后，越界后移除，击中目标后
     *
     * @param delta
     */
    @Override
    public void act(float delta) {
        super.act(delta);
        this.x = getX();
        this.y = getY();
        switch (direction) {
            case UP:
                y += speed;
                break;
            case DOWN:
                y -= speed;
                break;
            case LEFT:
                x -= speed;
                break;
            case RIGHT:
                x += speed;
                break;
        }
        if (x > limitX-bullet.getRegionWidth() || y > limitY-bullet.getRegionHeight() || x <0 || y < 0) {
            Stage stage = getStage();
            if (stage instanceof Shoot) {
                ((Shoot) stage).getHit().play();
            }
            stage.getRoot().removeActor(this); //出界了
            return;
        }
        setPosition(x, y);
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        super.draw(batch, parentAlpha);
        // 如果 region 为 null 或者 演员不可见, 则直接不绘制
        if (bullet == null || !isVisible()) {
            return;
        }
        batch.draw(
                bullet,
                getX(), getY(),
                getOriginX(), getOriginY(),
                getWidth(), getHeight(),
                getScaleX(), getScaleY(),
                getRotation()
        );
    }
}
